/**
 * 项目API请求工具 (Axios版本)
 * 提供统一的接口请求方法
 */

import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'

// 定义API响应类型
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  error?: string
  message?: string
}

// 定义登录数据类型
interface LoginData {
  username: string
  password: string
}


// 创建axios实例
const apiClient: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可以在这里添加认证token等
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  (error) => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

// 通用请求方法
const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  try {
    const response: AxiosResponse<T> = await apiClient(config)
    return {
      success: true,
      data: response.data,
    }
  } catch (error: any) {
    return {
      success: false,
      error: error.message || '请求失败',
      message: error.response?.data?.message || '未知错误',
    }
  }
}

// GET请求
export const get = async <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'GET',
    url,
    ...config,
  })
}

// POST请求
export const post = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'POST',
    url,
    data,
    ...config,
  })
}

// PUT请求
export const put = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'PUT',
    url,
    data,
    ...config,
  })
}

// DELETE请求
export const del = async <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'DELETE',
    url,
    ...config,
  })
}

// 登录接口
export const login = async (loginData: LoginData): Promise<ApiResponse> => {
  return post('/auth/login', loginData)
}

// 发送验证码接口
export const sendSmsCode = async (phone: string): Promise<ApiResponse> => {
  return post('/auth/sms-code', { phone })
}

// 手机验证码登录接口
export const smsLogin = async (phone: string, code: string): Promise<ApiResponse> => {
  return post('/auth/sms-login', { phone, code })
}

// 用户信息接口
export const getUserInfo = async <T = any>(): Promise<ApiResponse<T>> => {
  return get('/user/info')
}

// 示例：获取图片列表接口
export const getImages = async <T = any>(): Promise<ApiResponse<T>> => {
  return get('/images')
}

// 示例：获取视频列表接口
export const getVideos = async <T = any>(): Promise<ApiResponse<T>> => {
  return get('/videos')
}

// 示例：获取音乐列表接口
export const getMusicList = async <T = any>(): Promise<ApiResponse<T>> => {
  return get('/music')
}

export default {
  get,
  post,
  put,
  del,
  login,
  sendSmsCode,
  smsLogin,
  getUserInfo,
  getImages,
  getVideos,
  getMusicList,
}